#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/7/22  13:49
# @Author: 余浪人
# @email: yulangren520@gmail.com
import os
from pathlib import Path
from apps import get_sys_url
from apps.control import sys_bp
import requests, time, re, json, base64
from apps.models.member_model import TL_Member_Model, db
from apps.lib.user_login import parse_quote, createCookie, get_token
from flask_login import login_required, login_user, current_user, logout_user
from flask import request, render_template, jsonify, redirect, url_for, current_app
from apps.forms.member_form import TL_Member_Form, TL_Login_Form, TL_Member_Edit_Form
from apps.lib.public import add_data, real_delete_data, check_obj, edit_data, check_password, errors, real_deletes, page_auto, redis_, create_hash, del_not_day30


@sys_bp.route('/member_list', endpoint='member_list', methods=['GET', 'DELETE', 'DELETES'])
@login_required
def member_list():
    if request.method == 'DELETE':
        uid = request.form.get('uid')
        member = TL_Member_Model.query.filter_by(id=uid).first()
        if not check_obj(member):
            if member.id != 1:
                return real_delete_data(TL_Member_Model, db, uid)
            return jsonify({"status": 1, "msg": "超级管理员不可删除!"})
    elif request.method == 'DELETES':
        return real_deletes(TL_Member_Model, db, request.form.get('id_array').split('#TL#'))
    data_list, page = page_auto(TL_Member_Model.query.order_by(TL_Member_Model.id.desc()))
    return render_template('system_template/member_list.html', data_list=data_list, page=page)


@sys_bp.route('/member_add', endpoint='member_add', methods=['GET', 'POST'])
@login_required
def member_add():
    if request.method == 'POST':
        return add_data(TL_Member_Model, TL_Member_Form, db)
    return render_template('system_template/member.html', form=TL_Member_Form(request.form))


@sys_bp.route('/member_edit', endpoint='member_edit', methods=['GET', 'POST'])
@login_required
def member_edit():
    member = TL_Member_Model.query.filter_by(id=current_user.id).first()
    if request.method == 'POST' and not check_obj(member):
        return edit_data(TL_Member_Edit_Form, TL_Member_Model, db, current_user.id)
    if not check_obj(member):
        return render_template('system_template/member.html', form=TL_Member_Edit_Form(data=dict(member)))


@sys_bp.route('/bind_code', endpoint='bind_code', methods=['GET'])
@login_required
def bind_code():
    r_0 = redis_(db=0)
    raw_cookies = r_0.get(str(request.remote_addr))
    if raw_cookies:
        cookies = json.loads(raw_cookies)
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
                   'Cookie': createCookie(cookies)}
        u1 = parse_quote('https://graph.qq.com/oauth2.0/login_jump')
        token = get_token(cookies["qrsig"])
        sjc = int(time.time() * 1000)
        appId = current_app.config.get('APP_ID')
        login_sig = cookies["pt_login_sig"]
        url = f"https://ssl.ptlogin2.qq.com/ptqrlogin?u1={u1}&ptqrtoken={token}&ptredirect=0&h=1&t=1&g=1&from_ui=1&ptlang=2052&action=0-0-{sjc}&js_ver=19091015&js_type=1&login_sig={login_sig}&pt_uistyle=40&aid=716027609&daid=377&pt_3rd_aid={appId}&"
        verify_login = requests.get(url, headers=headers)
        data = eval(verify_login.text.replace('ptuiCB', ''))
        if data[0] == '0' and '登录成功' in data[-2]:
            cookie = requests.utils.dict_from_cookiejar(verify_login.cookies)
            sKey, rk = cookie['skey'], create_hash(cookie['uin'])
            obj = TL_Member_Model.query.filter_by(uuid=current_user.uuid).first()
            if not check_obj(obj) and obj:
                try:
                    obj.set_attrs({'user_rk': rk})
                    db.session.commit()
                    r_0.delete(str(request.remote_addr))
                    return jsonify({'status': 0, 'msg': '绑定成功'})
                except:
                    db.session.rollback()
            return jsonify({'status': 4, 'msg': '绑定失败'})
        elif data[0] == '66':
            return jsonify({'status': 2, 'msg': '二维码未失效'})
        elif data[0] == '67':
            return jsonify({'status': 3, 'msg': '二维码认证中'})
    return jsonify({'status': 1, 'msg': '请重新后去二维码！'})


@sys_bp.route('/bind_account_html', endpoint='bind_account_html', methods=['GET'])
@login_required
def bind_account_html():
    return render_template('system_template/account_bind.html')


@sys_bp.route('/admin', endpoint='member_login', methods=['GET', 'POST'])
def member_login():
    form = TL_Login_Form(request.form)
    if request.method == 'POST':
        username = request.form.get('username').strip()
        password = request.form.get('password')
        if form.validate() and username and password:
            obj = TL_Member_Model.query.filter_by(username=username).first()
            if not check_obj(obj) and obj:  # 验证密码
                login_user(obj)
                if check_password(obj.password, password):
                    return jsonify({"status": 0, "msg": "登录成功!"})
                return jsonify({"status": 1, "msg": "用户密码错误!"})
        return jsonify({"status": 1, "msg": errors(form)})
    setting = Path(os.path.join(get_sys_url(), 'apps/setting.json'))
    if not setting.exists() and not current_app.config.get('SQLALCHEMY_DATABASE_URI', ''): return redirect(url_for('sys_bp.install'))
    del_not_day30('tl_visit_num')
    return render_template('system_template/login.html')


@sys_bp.route('/logout', endpoint='logout', methods=['GET'])
@login_required
def logout():
    logout_user()
    return redirect(url_for('sys_bp.member_login'))


@sys_bp.route('/qqCode', endpoint='qqCode', methods=['GET'])
def get_Vcode():
    session = requests.session()
    sjc = int(time.time() * 1000)
    appId = current_app.config.get('APP_ID')
    webSite = current_app.config.get('REDIRECT_URI').split('/')[2]  # specimen.vip
    redirect_uri = parse_quote(current_app.config.get('REDIRECT_URI'))  # 回调地址url
    start_url = f'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={appId}&redirect_uri={redirect_uri}&state=login'
    try:
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'}
        res = session.get(start_url, headers=headers)
        param = re.findall('appid=(\d+)&daid=(\d+)&style', res.text)[0]
        param_0, param_1 = param[0], param[-1]
        v_img = f'https://ssl.ptlogin2.qq.com/ptqrshow?appid={param_0}&e=2&l=M&s=3&d=72&v=4&t={sjc}&daid={param_1}&pt_3rd_aid={appId}'
        response_img = session.get(v_img)
        cookies = requests.utils.dict_from_cookiejar(response_img.cookies)
        url = f'https://xui.ptlogin2.qq.com/cgi-bin/xlogin?appid=716027609&daid=383&style=33&login_text=授权并登录&hide_title_bar=1&hide_border=1&target=self&s_url=https://graph.qq.com/oauth2.0/login_jump&pt_3rd_aid={appId}&pt_feedback_link=https://support.qq.com/products/77942?customInfo={webSite}.appid{appId}'
        response = session.get(url)
        cookies.update(requests.utils.dict_from_cookiejar(response.cookies))
        r_0 = redis_(db=0)
        r_0.set(str(request.remote_addr), json.dumps(cookies), 10 * 60)  # 将cookie写入redis中 》 key为IP | 有效期为10分钟
        code_base64 = base64.b64encode(response_img.content).decode('utf-8')
        img = 'data:image/jpg;base64,' + code_base64
        return jsonify({'status': 0, 'msg': 'success', 'data': img})  # 返回图片base64码
    except:
        return jsonify({'status': 4, 'msg': 'error'})


@sys_bp.route('/verify_user', endpoint='verify_user', methods=['GET'])
def verify_user():
    r_0 = redis_(db=0)
    raw_cookies = r_0.get(str(request.remote_addr))
    if raw_cookies:
        cookies = json.loads(raw_cookies)
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
                   'Cookie': createCookie(cookies)}
        u1 = parse_quote('https://graph.qq.com/oauth2.0/login_jump')
        token = get_token(cookies["qrsig"])
        sjc = int(time.time() * 1000)
        appId = current_app.config.get('APP_ID')
        login_sig = cookies["pt_login_sig"]
        url = f"https://ssl.ptlogin2.qq.com/ptqrlogin?u1={u1}&ptqrtoken={token}&ptredirect=0&h=1&t=1&g=1&from_ui=1&ptlang=2052&action=0-0-{sjc}&js_ver=19091015&js_type=1&login_sig={login_sig}&pt_uistyle=40&aid=716027609&daid=377&pt_3rd_aid={appId}&"
        verify_login = requests.get(url, headers=headers)
        data = eval(verify_login.text.replace('ptuiCB', ''))
        if data[0] == '0' and '登录成功' in data[-2]:
            cookie = requests.utils.dict_from_cookiejar(verify_login.cookies)
            sKey, rk = cookie['skey'], create_hash(cookie['uin'])  # 根据提取的值与数据库中校验
            obj = TL_Member_Model.query.filter(TL_Member_Model.user_rk == rk, TL_Member_Model.status == 1).first()
            if obj:
                login_user(obj)
                r_0.delete(str(request.remote_addr))
                return jsonify({'status': 0, 'msg': '登录成功！', 'location': url_for('sys_bp.base_frame')})
            return jsonify({'status': 4, 'msg': '拒绝，没有权限！'})
        elif data[0] == '66':
            return jsonify({'status': 2, 'msg': '二维码未失效'})
        elif data[0] == '67':
            return jsonify({'status': 3, 'msg': '二维码认证中'})
    return jsonify({'status': 1, 'msg': '请重新后去二维码！'})
